package com.lgmshare.component.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

import androidx.annotation.DrawableRes;
import androidx.annotation.RawRes;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片工具
 *
 * @author: lim
 * @description: 图片工具
 * @email: lgmshare@gmail.com
 * @datetime: 2014年6月3日 下午4:02:29
 */
public class ImageUtils {

    /**
     * 各种格式对应的字节大小：
     * ALPHA_8   ->不存储颜色信息,只存储透明度 ->一个像素占1个字节
     * RGB_565   ->一个像素点占16位          ->2个字节
     * ARGB_4444 ->一个像素点占16位          ->2个字节
     * ARGB_8888 ->一个像素点占32位          ->4个字节
     * RGBA_F16  ->一个像素点占64位          ->8个字节
     */

    //图片质量
    private static final int JPEG_QUALITY = 80;
    private static final int JPEG_QUALITY_LOW = 50;
    private static final int JPEG_QUALITY_HQ = 100;

    private ImageUtils() {
    }

    /**
     * 获取bitmap  以最省内存的方式读取本地资源的图片
     *
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap getBitmapFromRaw(Context context, @RawRes int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Config.RGB_565;
        // 获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * 获取bitmap
     *
     * @param resId     资源id
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmapFromRaw(Context context, @RawRes int resId, int maxWidth, int maxHeight) {
        if (context == null) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        InputStream is = context.getResources().openRawResource(resId);
        BitmapFactory.decodeStream(is, null, options);
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeStream(is, null, options);
    }

    /**
     * 获取bitmap 以最省内存的方式读取本地资源的图片 或者SDCard中的图片
     *
     * @param filePath  图片在SDCard中的路径
     * @return
     */
    public static Bitmap getBitmapFromSDCard(String filePath) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Config.RGB_565;
        // 获取资源图片
        return BitmapFactory.decodeFile(filePath, opt);
    }

    /**
     * 获取bitmap 通过文件名从Assets中获得资源，以位图的形式返回
     *
     * @param context
     * @param fileName 文件名应为assets文件下载绝对路径
     * @return 以位图的形式返回
     */
    public static Bitmap getBitmapFormAssets(Context context, String fileName) {
        Bitmap bitmap = null;
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取bitmap
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        try {
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            InputStream in = context.getContentResolver().openInputStream(uri);
            return BitmapFactory.decodeStream(in, null, bitmapOptions);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取bitmap
     *
     * @param file 文件
     * @return bitmap
     */
    public static Bitmap getBitmap(File file) {
        if (file == null) {
            return null;
        }
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(file));
            return BitmapFactory.decodeStream(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            FileUtils.closeIO(is);
        }
    }

    /**
     * 获取bitmap
     *
     * @param file      文件
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmap(File file, int maxWidth, int maxHeight) {
        if (file == null) {
            return null;
        }
        InputStream is = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            is = new BufferedInputStream(new FileInputStream(file));
            BitmapFactory.decodeStream(is, null, options);
            options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeStream(is, null, options);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            FileUtils.closeIO(is);
        }
    }

    /**
     * 获取bitmap
     *
     * @param filePath 文件路径
     * @return bitmap
     */
    public static Bitmap getBitmap(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        return BitmapFactory.decodeFile(filePath);
    }

    /**
     * 获取bitmap
     *
     * @param filePath  文件路径
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmap(String filePath, int maxWidth, int maxHeight) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 获取bitmap
     *
     * @param is        输入流
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmap(InputStream is, int maxWidth, int maxHeight) {
        if (is == null) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(is, null, options);
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeStream(is, null, options);
    }

    /**
     * 获取bitmap
     *
     * @param data      数据
     * @param offset    偏移量
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmap(byte[] data, int offset, int maxWidth, int maxHeight) {
        if (data.length == 0) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, offset, data.length, options);
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(data, offset, data.length, options);
    }

    /**
     * 获取bitmap
     *
     * @param res   资源对象
     * @param resId 资源id
     * @return bitmap
     */
    public static Bitmap getBitmap(Resources res, @DrawableRes int resId) {
        if (res == null) {
            return null;
        }
        return BitmapFactory.decodeResource(res, resId);
    }

    /**
     * 获取bitmap
     *
     * @param res       资源对象
     * @param resId     资源id
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmap(Resources res, @DrawableRes int resId, int maxWidth, int maxHeight) {
        if (res == null) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /**
     * 获取bitmap
     *
     * @param fd 文件描述
     * @return bitmap
     */
    public static Bitmap getBitmap(FileDescriptor fd) {
        if (fd == null) {
            return null;
        }
        return BitmapFactory.decodeFileDescriptor(fd);
    }

    /**
     * 获取bitmap
     *
     * @param fd        文件描述
     * @param maxWidth  最大宽度
     * @param maxHeight 最大高度
     * @return bitmap
     */
    public static Bitmap getBitmap(FileDescriptor fd, int maxWidth, int maxHeight) {
        if (fd == null) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);
        options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    }

    //----------------------------------------------------------

    /**
     * 图片保存
     *
     * @param bitmap
     * @param filePath
     * @throws IOException
     */
    public static void save(Bitmap bitmap, String filePath) throws IOException {
        save(bitmap, filePath, Bitmap.CompressFormat.JPEG, JPEG_QUALITY_HQ);
    }

    /**
     * 图片保存
     *
     * @param filePath
     * @param bitmap
     * @param quality  保存质量
     * @throws IOException
     */
    public static void save(Bitmap bitmap, String filePath, int quality) throws IOException {
        save(bitmap, filePath, Bitmap.CompressFormat.JPEG, quality);
    }

    /**
     * 图片保存
     *
     * @param bitmap
     * @param filePath
     * @param format
     * @param quality
     * @throws IOException
     */
    public static void save(Bitmap bitmap, String filePath, Bitmap.CompressFormat format, int quality) throws IOException {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(filePath);
            bitmap.compress(format, quality, outputStream);
            outputStream.close();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * @param context
     * @param imagePath android10及以上必须是app能访问到的路径（专属目录）
     * @param title
     * @param desc
     */
    public void saveImage(Context context, String imagePath, String title, String desc) {
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, title, desc);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void saveImage(Context context, Bitmap bitmap, String title, String desc) {
        MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, title, desc);
    }

    //----------------------------------------------------------

    /**
     * bitmap转byteArr
     *
     * @param bitmap
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bitmap) {
        return bitmap2Bytes(bitmap, Bitmap.CompressFormat.JPEG, JPEG_QUALITY_HQ);
    }

    /**
     * bitmap转byteArr
     *
     * @param bitmap
     * @param format
     * @param quality
     * @return
     */
    public static byte[] bitmap2Bytes(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
        ByteArrayOutputStream outputStream = null;
        try {
            outputStream = new ByteArrayOutputStream();
            bitmap.compress(format, quality, outputStream);
            return outputStream.toByteArray();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //----------------------------------------------------------

    /**
     * 缩放图片
     *
     * @param bitmap    源图片
     * @param newWidth  新宽度
     * @param newHeight 新高度
     * @return 缩放后的图片
     */
    public static Bitmap scale(Bitmap bitmap, int newWidth, int newHeight) {
        return scale(bitmap, newWidth, newHeight, false);
    }

    /**
     * 缩放图片
     *
     * @param bitmap    源图片
     * @param newWidth  新宽度
     * @param newHeight 新高度
     * @param recycle   是否回收
     * @return 缩放后的图片
     */
    public static Bitmap scale(Bitmap bitmap, int newWidth, int newHeight, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        Bitmap ret = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 缩放图片
     *
     * @param bitmap      源图片
     * @param scaleWidth  缩放宽度倍数
     * @param scaleHeight 缩放高度倍数
     * @return 缩放后的图片
     */
    public static Bitmap scale(Bitmap bitmap, float scaleWidth, float scaleHeight) {
        return scale(bitmap, scaleWidth, scaleHeight, false);
    }

    /**
     * 缩放图片
     *
     * @param bitmap      源图片
     * @param scaleWidth  缩放宽度倍数
     * @param scaleHeight 缩放高度倍数
     * @param recycle     是否回收
     * @return 缩放后的图片
     */
    public static Bitmap scale(Bitmap bitmap, float scaleWidth, float scaleHeight, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.setScale(scaleWidth, scaleHeight);
        Bitmap ret = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 裁剪图片
     *
     * @param bitmap 源图片
     * @param x      开始坐标x
     * @param y      开始坐标y
     * @param width  裁剪宽度
     * @param height 裁剪高度
     * @return 裁剪后的图片
     */
    public static Bitmap clip(Bitmap bitmap, int x, int y, int width, int height) {
        return clip(bitmap, x, y, width, height, false);
    }

    /**
     * 裁剪图片
     *
     * @param bitmap  源图片
     * @param x       开始坐标x
     * @param y       开始坐标y
     * @param width   裁剪宽度
     * @param height  裁剪高度
     * @param recycle 是否回收
     * @return 裁剪后的图片
     */
    public static Bitmap clip(Bitmap bitmap, int x, int y, int width, int height, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        Bitmap ret = Bitmap.createBitmap(bitmap, x, y, width, height);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 倾斜图片
     *
     * @param bitmap 源图片
     * @param kx     倾斜因子x
     * @param ky     倾斜因子y
     * @return 倾斜后的图片
     */
    public static Bitmap skew(Bitmap bitmap, float kx, float ky) {
        return skew(bitmap, kx, ky, 0, 0, false);
    }

    /**
     * 倾斜图片
     *
     * @param bitmap  源图片
     * @param kx      倾斜因子x
     * @param ky      倾斜因子y
     * @param recycle 是否回收
     * @return 倾斜后的图片
     */
    public static Bitmap skew(Bitmap bitmap, float kx, float ky, boolean recycle) {
        return skew(bitmap, kx, ky, 0, 0, recycle);
    }

    /**
     * 倾斜图片
     *
     * @param bitmap 源图片
     * @param kx     倾斜因子x
     * @param ky     倾斜因子y
     * @param px     平移因子x
     * @param py     平移因子y
     * @return 倾斜后的图片
     */
    public static Bitmap skew(Bitmap bitmap, float kx, float ky, float px, float py) {
        return skew(bitmap, kx, ky, px, py, false);
    }

    /**
     * 倾斜图片
     *
     * @param bitmap  源图片
     * @param kx      倾斜因子x
     * @param ky      倾斜因子y
     * @param px      平移因子x
     * @param py      平移因子y
     * @param recycle 是否回收
     * @return 倾斜后的图片
     */
    public static Bitmap skew(Bitmap bitmap, float kx, float ky, float px, float py, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.setSkew(kx, ky, px, py);
        Bitmap ret = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 旋转图片
     *
     * @param bitmap  源图片
     * @param degrees 旋转角度
     * @param px      旋转点横坐标
     * @param py      旋转点纵坐标
     * @return 旋转后的图片
     */
    public static Bitmap rotate(Bitmap bitmap, int degrees, float px, float py) {
        return rotate(bitmap, degrees, px, py, false);
    }

    /**
     * 旋转图片
     *
     * @param bitmap  源图片
     * @param degrees 旋转角度
     * @param px      旋转点横坐标
     * @param py      旋转点纵坐标
     * @param recycle 是否回收
     * @return 旋转后的图片
     */
    public static Bitmap rotate(Bitmap bitmap, int degrees, float px, float py, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        if (degrees == 0) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.setRotate(degrees, px, py);
        Bitmap ret = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 转为圆形图片
     *
     * @param bitmap 源图片
     * @return 圆形图片
     */
    public static Bitmap toRound(Bitmap bitmap) {
        return toRound(bitmap, false);
    }

    /**
     * 转为圆形图片
     *
     * @param bitmap  源图片
     * @param recycle 是否回收
     * @return 圆形图片
     */
    public static Bitmap toRound(Bitmap bitmap, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int radius = Math.min(width, height) >> 1;
        Bitmap ret = bitmap.copy(bitmap.getConfig(), true);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(ret);
        Rect rect = new Rect(0, 0, width, height);
        paint.setAntiAlias(true);
        paint.setColor(Color.TRANSPARENT);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawCircle(width >> 1, height >> 1, radius, paint);
        canvas.drawBitmap(bitmap, rect, rect, paint);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 转为圆角图片
     *
     * @param bitmap 源图片
     * @param radius 圆角的度数
     * @return 圆角图片
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int radius) {
        return toRoundCorner(bitmap, radius, false);
    }

    /**
     * 转为圆角图片
     *
     * @param bitmap  源图片
     * @param radius  圆角的度数
     * @param recycle 是否回收
     * @return 圆角图片
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int radius, boolean recycle) {
        if (null == bitmap) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap ret = bitmap.copy(bitmap.getConfig(), true);
        BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(ret);
        RectF rectf = new RectF(0, 0, width, height);
        paint.setAntiAlias(true);
        paint.setShader(bitmapShader);
        canvas.drawRoundRect(rectf, radius, radius, paint);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 转换图片成圆形
     *
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public static Bitmap toCricle(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }

    /**
     * 快速模糊
     * <p>先缩小原图，对小图进行模糊，再放大回原先尺寸</p>
     *
     * @param bitmap 源图片
     * @param scale  缩小倍数(0...1)
     * @param radius 模糊半径
     * @return 模糊后的图片
     */
    public static Bitmap fastBlur(Context context, Bitmap bitmap, float scale, float radius) {
        return fastBlur(context, bitmap, scale, radius, false);
    }

    /**
     * 快速模糊
     * <p>先缩小原图，对小图进行模糊，再放大回原先尺寸</p>
     *
     * @param context
     * @param bitmap  源图片
     * @param scale   缩小倍数(0...1)
     * @param radius  模糊半径
     * @param recycle 是否回收
     * @return 模糊后的图片
     */
    public static Bitmap fastBlur(Context context, Bitmap bitmap, float scale, float radius, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int scaleWidth = (int) (width * scale + 0.5f);
        int scaleHeight = (int) (height * scale + 0.5f);
        if (scaleWidth == 0 || scaleHeight == 0) {
            return null;
        }
        Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, scaleWidth, scaleHeight, true);
        Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
        Canvas canvas = new Canvas();
        PorterDuffColorFilter filter = new PorterDuffColorFilter(
                Color.TRANSPARENT, PorterDuff.Mode.SRC_ATOP);
        paint.setColorFilter(filter);
        canvas.scale(scale, scale);
        canvas.drawBitmap(scaleBitmap, 0, 0, paint);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            scaleBitmap = renderScriptBlur(context, scaleBitmap, radius);
        } else {
            scaleBitmap = stackBlur(scaleBitmap, (int) radius, true);
        }
        if (scale == 1) {
            return scaleBitmap;
        }
        Bitmap ret = Bitmap.createScaledBitmap(scaleBitmap, width, height, true);
        destroyBitmap(scaleBitmap);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * renderScript模糊图片
     * <p>API大于17</p>
     *
     * @param context
     * @param bitmap  源图片
     * @param radius  模糊度(0...25)
     * @return 模糊后的图片
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap renderScriptBlur(Context context, Bitmap bitmap, float radius) {
        if (isEmptyBitmap(bitmap)) return null;
        RenderScript rs = null;
        try {
            rs = RenderScript.create(context);
            rs.setMessageHandler(new RenderScript.RSMessageHandler());
            Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation
                    .USAGE_SCRIPT);
            Allocation output = Allocation.createTyped(rs, input.getType());
            ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            if (radius > 25) {
                radius = 25.0f;
            } else if (radius <= 0) {
                radius = 1.0f;
            }
            blurScript.setInput(input);
            blurScript.setRadius(radius);
            blurScript.forEach(output);
            output.copyTo(bitmap);
        } finally {
            if (rs != null) {
                rs.destroy();
            }
        }
        return bitmap;
    }

    /**
     * stack模糊图片
     *
     * @param bitmap  源图片
     * @param radius  模糊半径
     * @param recycle 是否回收
     * @return stackBlur模糊图片
     */
    public static Bitmap stackBlur(Bitmap bitmap, int radius, boolean recycle) {
        Bitmap ret;
        if (recycle) {
            ret = bitmap;
        } else {
            ret = bitmap.copy(bitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = ret.getWidth();
        int h = ret.getHeight();

        int[] pix = new int[w * h];
        ret.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int[] r = new int[wh];
        int[] g = new int[wh];
        int[] b = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int[] vmin = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int[] dv = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }
        ret.setPixels(pix, 0, w, 0, 0, w, h);
        return (ret);
    }

    /**
     * 添加颜色边框
     *
     * @param bitmap      源图片
     * @param borderWidth 边框宽度
     * @param color       边框的颜色值
     * @return 带颜色边框图
     */
    public static Bitmap addFrame(Bitmap bitmap, int borderWidth, int color) {
        return addFrame(bitmap, borderWidth, color, false);
    }

    /**
     * 添加颜色边框
     *
     * @param bitmap      源图片
     * @param borderWidth 边框宽度
     * @param color       边框的颜色值
     * @param recycle     是否回收
     * @return 带颜色边框图
     */
    public static Bitmap addFrame(Bitmap bitmap, int borderWidth, int color, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        int newWidth = bitmap.getWidth() + borderWidth >> 1;
        int newHeight = bitmap.getHeight() + borderWidth >> 1;
        Bitmap newBitmap = Bitmap.createBitmap(newWidth, newHeight, bitmap.getConfig());
        Canvas canvas = new Canvas(newBitmap);
        Rect rec = canvas.getClipBounds();
        Paint paint = new Paint();
        paint.setColor(color);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(borderWidth);
        canvas.drawRect(rec, paint);
        canvas.drawBitmap(bitmap, borderWidth, borderWidth, null);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return newBitmap;
    }

    /**
     * 添加倒影
     *
     * @param bitmap           源图片的
     * @param reflectionHeight 倒影高度
     * @return 带倒影图片
     */
    public static Bitmap addReflection(Bitmap bitmap, int reflectionHeight) {
        return addReflection(bitmap, reflectionHeight, false);
    }

    /**
     * 添加倒影
     *
     * @param bitmap           源图片的
     * @param reflectionHeight 倒影高度
     * @param recycle          是否回收
     * @return 带倒影图片
     */
    public static Bitmap addReflection(Bitmap bitmap, int reflectionHeight, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        final int REFLECTION_GAP = 0;
        int srcWidth = bitmap.getWidth();
        int srcHeight = bitmap.getHeight();
        if (0 == srcWidth || srcHeight == 0) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionBitmap = Bitmap.createBitmap(bitmap, 0, srcHeight - reflectionHeight,
                srcWidth, reflectionHeight, matrix, false);
        if (null == reflectionBitmap) {
            return null;
        }
        Bitmap ret = Bitmap.createBitmap(srcWidth, srcHeight + reflectionHeight, bitmap.getConfig());
        Canvas canvas = new Canvas(ret);
        canvas.drawBitmap(bitmap, 0, 0, null);
        canvas.drawBitmap(reflectionBitmap, 0, srcHeight + REFLECTION_GAP, null);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        LinearGradient shader = new LinearGradient(0, srcHeight, 0,
                ret.getHeight() + REFLECTION_GAP,
                0x70FFFFFF, 0x00FFFFFF, Shader.TileMode.MIRROR);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(
                PorterDuff.Mode.DST_IN));
        canvas.save();
        canvas.drawRect(0, srcHeight, srcWidth,
                ret.getHeight() + REFLECTION_GAP, paint);
        canvas.restore();
        destroyBitmap(reflectionBitmap);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 添加文字水印
     *
     * @param bitmap   源图片
     * @param content  水印文本
     * @param textSize 水印字体大小
     * @param color    水印字体颜色
     * @param alpha    水印字体透明度
     * @param x        起始坐标x
     * @param y        起始坐标y
     * @return 带有文字水印的图片
     */
    public static Bitmap addTextWatermark(Bitmap bitmap, String content, int textSize, int color, int alpha, float x, float y) {
        return addTextWatermark(bitmap, content, textSize, color, alpha, x, y, false);
    }

    /**
     * 添加文字水印
     *
     * @param bitmap   源图片
     * @param content  水印文本
     * @param textSize 水印字体大小
     * @param color    水印字体颜色
     * @param alpha    水印字体透明度
     * @param x        起始坐标x
     * @param y        起始坐标y
     * @param recycle  是否回收
     * @return 带有文字水印的图片
     */
    public static Bitmap addTextWatermark(Bitmap bitmap, String content, int textSize, int color, int alpha, float x, float y, boolean recycle) {
        if (isEmptyBitmap(bitmap) || content == null) {
            return null;
        }
        Bitmap ret = bitmap.copy(bitmap.getConfig(), true);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        Canvas canvas = new Canvas(ret);
        paint.setAlpha(alpha);
        paint.setColor(color);
        paint.setTextSize(textSize);
        Rect bounds = new Rect();
        paint.getTextBounds(content, 0, content.length(), bounds);
        canvas.drawText(content, x, y, paint);
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 添加图片水印
     *
     * @param bitmap    源图片
     * @param watermark 图片水印
     * @param x         起始坐标x
     * @param y         起始坐标y
     * @param alpha     透明度
     * @return 带有图片水印的图片
     */
    public static Bitmap addImageWatermark(Bitmap bitmap, Bitmap watermark, int x, int y, int alpha) {
        return addImageWatermark(bitmap, watermark, x, y, alpha, false);
    }

    /**
     * 添加图片水印
     *
     * @param bitmap    源图片
     * @param watermark 图片水印
     * @param x         起始坐标x
     * @param y         起始坐标y
     * @param alpha     透明度
     * @param recycle   是否回收
     * @return 带有图片水印的图片
     */
    public static Bitmap addImageWatermark(Bitmap bitmap, Bitmap watermark, int x, int y, int alpha, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        Bitmap ret = bitmap.copy(bitmap.getConfig(), true);
        if (!isEmptyBitmap(watermark)) {
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            Canvas canvas = new Canvas(ret);
            paint.setAlpha(alpha);
            canvas.drawBitmap(watermark, x, y, paint);
        }
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 转为alpha位图
     *
     * @param bitmap 源图片
     * @return alpha位图
     */
    public static Bitmap toAlpha(Bitmap bitmap) {
        return toAlpha(bitmap, false);
    }

    /**
     * 转为alpha位图
     *
     * @param bitmap  源图片
     * @param recycle 是否回收
     * @return alpha位图
     */
    public static Bitmap toAlpha(Bitmap bitmap, boolean recycle) {
        if (isEmptyBitmap(bitmap)) {
            return null;
        }
        Bitmap ret = bitmap.extractAlpha();
        if (recycle) {
            destroyBitmap(bitmap);
        }
        return ret;
    }

    /**
     * 将图片缩放到另一张图中
     *
     * @param bitmap     目标图
     * @param destBitmap 模板图
     */
    public static void zoomBitmap(Bitmap bitmap, Bitmap destBitmap) {
        zoomBitmap(bitmap, destBitmap, Color.TRANSPARENT);
    }

    /**
     * 将图片缩放到另一张图中
     *
     * @param bitmap     目标图
     * @param destBitmap 模板图
     * @param clearColor 抹除颜色
     */
    public static void zoomBitmap(Bitmap bitmap, Bitmap destBitmap, int clearColor) {
        zoomBitmap(bitmap, destBitmap, clearColor, 0, 0, bitmap.getWidth(), bitmap.getHeight(), 0, 0, destBitmap.getWidth(), destBitmap.getHeight());
    }

    /**
     * @param bitmap     目标图
     * @param destBitmap 模板图
     * @param clearColor 抹除颜色
     * @param x
     * @param y
     * @param sw
     * @param sh
     * @param dx
     * @param dy
     * @param dw
     * @param dh
     */
    public static void zoomBitmap(Bitmap bitmap, Bitmap destBitmap, int clearColor, int x, int y, int sw, int sh, int dx, int dy, int dw, int dh) {
        destBitmap.eraseColor(clearColor);
        Canvas canvas = new Canvas(destBitmap);
        Paint paint = new Paint();
        paint.setFilterBitmap(true);
        canvas.drawBitmap(bitmap, new Rect(x + 1, y + 1, sw - 1, sh - 1), new Rect(dx, dy, dw, dh), paint);
        canvas.setBitmap(null);
    }

    //----------------------------------------------------------

    /**
     * 压缩图片
     *
     * @param imageFile      图片文件
     * @param reqWidth       图片最大宽度
     * @param reqHeight      图片最大高度
     * @param compressFormat 图片格式
     * @param quality        图片质量
     * @param saveFilePath   指定压缩后图片保存路径
     * @return
     * @throws IOException
     */
    public static File compress(File imageFile, int reqWidth, int reqHeight, Bitmap.CompressFormat compressFormat, int quality, String saveFilePath) throws IOException {
        File file = new File(saveFilePath).getParentFile();
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(saveFilePath);
            // write the compressed bitmap at the destination specified by saveFilePath.
            decodeSampledBitmapFromFile(imageFile, reqWidth, reqHeight).compress(compressFormat, quality, fileOutputStream);
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }

        return new File(saveFilePath);
    }

    private static Bitmap decodeSampledBitmapFromFile(File imageFile, int reqWidth, int reqHeight) throws IOException {
        // First decode with inJustDecodeBounds=true to check dimensions
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        Bitmap scaledBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);

        //check the rotation of the image and display it properly
        ExifInterface exif;
        exif = new ExifInterface(imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
        Matrix matrix = new Matrix();
        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
            matrix.postRotate(90);
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
            matrix.postRotate(180);
        } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
            matrix.postRotate(270);
        }
        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        return scaledBitmap;
    }

    /**
     * 计算采样大小
     *
     * @param options   选项
     * @param reqWidth  最大宽度
     * @param reqHeight 最大高度
     * @return 采样大小
     */
    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    private static float[] getValueSaturation() {
        float[] carray = new float[20];
        // 高饱和度
        carray[0] = 5;
        carray[1] = 0;
        carray[2] = 0;
        carray[3] = 0;
        carray[4] = -254;
        carray[5] = 0;
        carray[6] = 5;
        carray[7] = 0;
        carray[8] = 0;
        carray[9] = -254;
        carray[10] = 0;
        carray[11] = 0;
        carray[12] = 5;
        carray[13] = 0;
        carray[14] = -254;
        carray[15] = 0;
        carray[16] = 0;
        carray[17] = 0;
        carray[18] = 5;
        carray[19] = -254;
        return carray;
    }

    private static float[] getValueBlackAndWhite() {
        float[] carray = new float[20];
        // 黑白
        carray[0] = (float) 0.308;
        carray[1] = (float) 0.609;
        carray[2] = (float) 0.082;
        carray[3] = 0;
        carray[4] = 0;
        carray[5] = (float) 0.308;
        carray[6] = (float) 0.609;
        carray[7] = (float) 0.082;
        carray[8] = 0;
        carray[9] = 0;
        carray[10] = (float) 0.308;
        carray[11] = (float) 0.609;
        carray[12] = (float) 0.082;
        carray[13] = 0;
        carray[14] = 0;
        carray[15] = 0;
        carray[16] = 0;
        carray[17] = 0;
        carray[18] = 1;
        carray[19] = 0;
        return carray;
    }

    /**
     * 编辑图片大小，保持图片不变形。
     *
     * @param bitmap
     * @param resetWidth
     * @param resetHeight
     * @return
     */
    public static Bitmap toResetImage(Bitmap bitmap, int resetWidth, int resetHeight) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int tmpWidth;
        int tmpHeight;
        float scaleWidth = (float) resetWidth / (float) width;
        float scaleHeight = (float) resetHeight / (float) height;
        float maxTmpScale = scaleWidth >= scaleHeight ? scaleWidth : scaleHeight;
        // 保持不变形
        tmpWidth = (int) (maxTmpScale * width);
        tmpHeight = (int) (maxTmpScale * height);
        Matrix m = new Matrix();
        m.setScale(maxTmpScale, maxTmpScale, tmpWidth, tmpHeight);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, false);
        // 切图
        int x = (tmpWidth - resetWidth) / 2;
        int y = (tmpHeight - resetHeight) / 2;
        return Bitmap.createBitmap(bitmap, x, y, resetWidth, resetHeight);
    }

    /**
     * 图片去色,返回灰度图片
     *
     * @param bitmap 传入的图片
     * @return 去色后的图片
     */
    public static Bitmap toGrayScale(Bitmap bitmap) {
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        Bitmap ret = Bitmap.createBitmap(width, height, Config.RGB_565);
        Canvas canvas = new Canvas(ret);
        Paint paint = new Paint();
        paint.setColorFilter(null);
        canvas.drawBitmap(ret, 0, 0, paint);
        ColorMatrix cm = new ColorMatrix();
        cm.set(getValueBlackAndWhite());
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return ret;
    }

    /**
     * 去色同时加圆角
     *
     * @param bitmap 原图
     * @param pixels 圆角弧度
     * @return 修改后的图片
     */
    public static Bitmap toGrayScale(Bitmap bitmap, int pixels) {
        return toRoundCorner(toGrayScale(bitmap), pixels);
    }

    //----------------------------------------------------------

    /**
     * 生成图片倒影
     *
     * @param bitmap
     * @return
     */
    public static Bitmap createReflectedImage(Bitmap bitmap) {
        final int reflectionGap = 4;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.preScale(1, -1);
        Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);
        Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmapWithReflection);
        canvas.drawBitmap(bitmap, 0, 0, null);
        Paint defaultPaint = new Paint();
        canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
        canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
        Paint paint = new Paint();
        LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.MIRROR);
        paint.setShader(shader);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
        return bitmapWithReflection;
    }

    /**
     * 创建的包含文字的图片，背景为透明
     *
     * @param bitmap              图片
     * @param txtSize             文字大小
     * @param innerTxt            显示的文字
     * @param textColor           文字颜色Color.BLUE
     * @param textBackgroundColor 文字背景板颜色 Color.parseColor("#FFD700")
     * @return
     */
    public static Bitmap createTextImage(Bitmap bitmap, int txtSize, String innerTxt, int textColor, int textBackgroundColor) {
        int bitmapWidth = bitmap.getWidth();
        int bitmapHeight = bitmap.getHeight();

        int textWidth = txtSize * innerTxt.length();
        int textHeight = txtSize;

        int width;


        if (bitmapWidth > textWidth) {
            width = bitmapWidth + txtSize * innerTxt.length();
        } else {
            width = txtSize * innerTxt.length();
        }
        int height = bitmapHeight + txtSize;

        //若使背景为透明，必须设置为Bitmap.Config.ARGB_4444
        Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(bm);
        //把图片画上来
        Paint bitmapPaint = new Paint();
        canvas.drawBitmap(bitmap, (width - bitmapWidth) / 2, 0, bitmapPaint);


        Paint paint = new Paint();
        paint.setColor(textColor);
        paint.setTextSize(txtSize);
        paint.setAntiAlias(true);


        //计算得出文字的绘制起始x、y坐标
        int posX = (width - txtSize * innerTxt.length()) / 2;
        int posY = height / 2;

        int textX = posX + txtSize * innerTxt.length() / 4;

        Paint paint1 = new Paint();
        paint1.setColor(textBackgroundColor);
        paint1.setStrokeWidth(3);
        paint1.setStyle(Paint.Style.FILL_AND_STROKE);

        RectF r1 = new RectF();
        r1.left = posX;
        r1.right = posX + txtSize * innerTxt.length();
        r1.top = posY;
        r1.bottom = posY + txtSize;
        canvas.drawRoundRect(r1, 10, 10, paint1);
        canvas.drawText(innerTxt, textX, posY + txtSize - 2, paint);

        return bm;
    }

    /**
     * 图片旋转修复
     *
     * @param bitmap
     * @param exifOrientation
     * @return
     */
    private static Bitmap fixExif(Bitmap bitmap, int exifOrientation) {
        try {
            final Matrix bitmapMatrix = new Matrix();
            switch (exifOrientation) {
                case 1:
                    break;  // top left
                case 2:
                    bitmapMatrix.postScale(-1, 1);
                    break;  // top right
                case 3:
                    bitmapMatrix.postRotate(180);
                    break;  // bottom right
                case 4:
                    bitmapMatrix.postRotate(180);
                    bitmapMatrix.postScale(-1, 1);
                    break;  // bottom left
                case 5:
                    bitmapMatrix.postRotate(90);
                    bitmapMatrix.postScale(-1, 1);
                    break;  // left top
                case 6:
                    bitmapMatrix.postRotate(90);
                    break;  // right top
                case 7:
                    bitmapMatrix.postRotate(270);
                    bitmapMatrix.postScale(-1, 1);
                    break;  // right bottom
                case 8:
                    bitmapMatrix.postRotate(270);
                    break;  // left bottom
                default:
                    break;  // Unknown
            }

            // Create new originalBmp.
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), bitmapMatrix, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取图片旋转角度
     *
     * @param filePath 文件路径
     * @return 旋转角度
     */
    public static int getRotateDegree(String filePath) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(filePath);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                default:
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 获取图片缩放比例
     *
     * @param bitmapSize
     * @param maxPixels
     * @return
     */
    public static int getScaleFactor(BitmapSize bitmapSize, int maxPixels) {
        int scale = 1;
        int scaledW = bitmapSize.getWidth();
        int scaledH = bitmapSize.getHeight();
        while (scaledW * scaledH > maxPixels) {
            scale *= 2;
            scaledH /= 2;
            scaledW /= 2;
        }
        return scale;
    }

    /**
     * 可以对该图的非透明区域着色
     * <p>
     * 有多种使用场景，常见如 Button 的 pressed 状态，View 的阴影状态等
     *
     * @param bitmap
     * @param radius
     * @param color
     * @return
     */
    public static Bitmap getDropShadow(Bitmap bitmap, float radius, int color) {
        final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(color);

        final int width = bitmap.getWidth(), height = bitmap.getHeight();
        final Bitmap dest = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(dest);
        final Bitmap alpha = bitmap.extractAlpha();
        canvas.drawBitmap(alpha, 0, 0, paint);

        final BlurMaskFilter filter = new BlurMaskFilter(radius, BlurMaskFilter.Blur.OUTER);
        paint.setMaskFilter(filter);
        canvas.drawBitmap(alpha, 0, 0, paint);
        return bitmap;
    }

    /**
     * 缩略图工具类，
     * 可以根据本地视频文件源、
     * Bitmap 对象生成缩略图
     *
     * @param filePath
     * @param kind
     * @return
     */
    public static Bitmap getThumb(String filePath, int kind) {
        return ThumbnailUtils.createVideoThumbnail(filePath, kind);
    }

    public static Bitmap getThumb(Bitmap bitmap, int width, int height) {
        return ThumbnailUtils.extractThumbnail(bitmap, width, height);
    }

    /**
     * 图片资源回收
     *
     * @param bitmap
     */
    public static void destroyBitmap(Bitmap bitmap) {
        if (null != bitmap && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

    /**
     * 判断bitmap对象是否为空
     *
     * @param bitmap 源图片
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isEmptyBitmap(Bitmap bitmap) {
        return bitmap == null || bitmap.getWidth() == 0 || bitmap.getHeight() == 0;
    }

    /**
     * 获取图片尺寸
     *
     * @param filePath
     * @return
     */
    public static BitmapSize getImageSize(String filePath) {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);
        if (o.outWidth == 0 || o.outHeight == 0) {
            return null;
        }

        int w = o.outWidth;
        int h = o.outHeight;

        try {
            ExifInterface exif = new ExifInterface(filePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
            if (orientation == 5 || orientation == 6 || orientation == 7 || orientation == 8) {
                w = o.outHeight;
                h = o.outWidth;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new BitmapSize(w, h);
    }

    private static class BitmapSize {
        private int width;
        private int height;

        private BitmapSize(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }
    }
}
